New location:java.awt.Point[x=14,y=22]
import java.awt.*; // import the class library where Point is defined class AutoConvEg1 { public static void main ( String arg[] ) { Point pointA = new Point(); // create a point at x=0 y=0 short a=12, b=42; pointA.move( a, b ); // values in parameter list automatically // converted to the required type, int. System.out.println("New location:" + pointA ); } }
In the previous example,
converting from floating point to int
results in a loss of information,
so the programmer must explicitly ask for conversion with a type cast.
When a conversion from one type to another type
can be done without loss of
information,
the compiler will do it automatically.
For example,
the description of the move()
method says that
it requires two int
parameters:
public void move(int x, int y);
An int
value is held in 32 bits.
A short
value that is held in 16 bits can be converted to 32 bits
without loss of information.
So the modified program (above) will compile and run correctly.
The values inside variables a
and b
are not changed.
Those values are retrieved, then converted to
the types that the parameters require.
What will this program write to the monitor?